import request from '@/utils/request/doRequest'
import authority from '@/utils/authority'
import { isWx } from '@/utils/validate'

/**
 * @description: 获取手机验证
 * @param {String} phone 手机号
 * @return: Promise
 */
export const getCode = (phone, type = 'login') => {
  return request({
    url: '/api/app/v1/phone/code',
    method: 'post',
    data: {
      type,
      phone
    }
  })
}

/**
 * @description: 手机号和微信code登陆
 * @param {phone} Number 手机号
 * @param {code} Number 验证码
 * @param {wechat_code} Number 微信code
 * @return: Promise
 */
export const phoneLoginWx = async ({ phone, code, wechat_code }) => {
  authority.clear()
  const { user, token, visitor } = await request({
    url: '/api/miniapp/v1/login',
    method: 'post',
    data: {
      phone,
      code,
      wechat_code
    }
  })
  user.token = token
  user.visitor = visitor
  authority.set(user)
  return user
}

/**
 * @description: 手机号和微信code登陆
 * @param {phone} Number 手机号
 * @param {code} Number 验证码
 * @return: Promise
 */
export const phoneLoginUser = async ({ phone, code }) => {
  const { token, user } = await request({
    url: '/api/app/v1/login',
    method: 'post',
    data: {
      phone,
      code
    }
  })
  user.token = token
  authority.set(user)
  return user
}

export const phoneLogin = isWx ? phoneLoginWx : phoneLoginUser

export default phoneLogin
